<template>
  <el-card>
    <template #header>
      <h3>商品添加</h3>
    </template>

    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="70px"
      class="demo-ruleForm"
      size="mini"
    >
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="商品分类">
        <el-select
          v-model="ruleForm.cate"
          placeholder="请选择商品分类"
          prop="cate"
        >
          <el-option
            v-for="item in allCate"
            :key="item.cateName"
            :label="item.cateName"
            :value="item.cateName"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品价格" prop="price">
        <el-input-number
          v-model="ruleForm.price"
          :min="0"
          :max="100"
          label="描述文字"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="商品图片">
        <el-upload
          class="avatar-uploader"
          action="http://127.0.0.1:5000/goods/goods_img_upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品描述" prop="desc">
        <el-input
          type="textarea"
          :rows="4"
          placeholder="请输入内容"
          v-model="ruleForm.desc"
        >
        </el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')"
          >提交</el-button
        >
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { goodsCateList, addGoods } from '@/api/goods.js'
export default {
  data() {
    return {
      imageUrl: '',
      allCate: [],
      // 这是用来发请求时携带的url
      uploadUrl: '',
      ruleForm: {
        name: '',
        cate: '',
        price: '',
        desc: ''
      },
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        cate: [
          { required: true, message: '请选择商品分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请选择商品价格', trigger: 'change' }
        ],
        desc: [{ required: true, message: '请输入商品描述', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getAllCate()
  },
  methods: {
    // 提交
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          if (this.uploadUrl === '') {
            this.$message.error('请上传商品图片')
            return
          }
          // 当表单验证通过 则发起请求
          const data = await addGoods({
            name: this.ruleForm.name,
            category: this.ruleForm.cate,
            price: this.ruleForm.price,
            imgUrl: this.uploadUrl,
            goodsDesc: this.ruleForm.desc
          })
          if (data.code === 0) {
            this.$message({
              type: 'success',
              message: data.msg
            })
            this.resetForm(formName)
            this.$router.push('/goods/list')
          }
        } else {
          this.$message.error('添加失败')
          return false
        }
      })
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.uploadUrl = res.imgUrl
    },
    beforeAvatarUpload(file) {
      const arr = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
      // 判断当前图片的type类型是否在上面的数组中
      // arr.includes(file.type)
      const isJPG = arr.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    async getAllCate() {
      const { categories } = await goodsCateList()
      console.log(categories)
      this.allCate = categories
    }
  }
}
</script>

<style lang="less" scoped>
.el-input {
  width: 250px;
}
.el-select {
  width: 250px;
}
/deep/.el-form-item__label {
  width: 80px !important;
}
/deep/ .el-textarea {
  width: 400px;
}
/deep/ .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style>
